package com.yili.oa.test;

import com.github.pagehelper.PageHelper;
import com.yili.oa.entity.ExtractsRecordSearch;
import com.yili.oa.entity.FtAccountDetailsSearch;
import com.yili.oa.entity.FtBetRecordSearch;
import com.yili.oa.entity.SearchBase;
import com.yili.oa.models.*;
import com.yili.oa.service.*;
import com.yili.oa.service.impl.AdminSvImpl;
import com.yili.oa.vo.response.*;
import io.swagger.annotations.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/temp")
@Api("游戏接口")
public class TempController {

    @Autowired
    private AdminSvImpl adminService;

    @Autowired
    private DealersLevelService dealersLevelService;

    @Autowired
    private FtBetRecordService ftBetRecordService;

    @Autowired
    private RankingListService rankingListService;

    @Autowired
    private ExtractsRecordService extractsRecordService;

    @Autowired
    private FtAccountDetailsService ftAccountDetailsService;

    @Autowired
    private FtVipService ftVipService;

/*    @GetMapping("/dealer/{userId}")
    @ApiOperation(value = "代理-我的推广")
    public DealersInfoRes getUserDealerInfo(@ApiParam("用户id") @PathVariable("userId")String userId){
        //当前用户信息
        Admin admin = adminService.getByAccount(userId);
        //当前代理等级信息
        DealersLevel current = dealersLevelService.getById(admin.getLevelId());
        //下一及代理等级信息
        DealersLevel next = dealersLevelService.getNextLevel(admin.getLevelId());
        //直属玩家信息
        List<Admin> first = adminService.getUnderChildren(admin.getUsername());
        //二级代理信息
        List<Admin> second = new ArrayList<>();
        //三级代理信息
        List<Admin> third = new ArrayList<>();
        first.forEach(child -> {
            List<Admin> tempList = adminService.getUnderChildren(child.getUsername());
            tempList.forEach(temp-> {
                second.add(temp);
            });
        });
        second.forEach(child -> {
            List<Admin> tempList = adminService.getUnderChildren(child.getUsername());
            tempList.forEach(temp-> {
                third.add(temp);
            });
        });
        //直属玩家佣金
        BigDecimal[] firstBets = new BigDecimal[]{BigDecimal.ZERO};
        //二级三级玩家佣金
        BigDecimal[] secondBets = new BigDecimal[]{BigDecimal.ZERO};
        //二级三级玩家佣金
        BigDecimal[] thirdBets = new BigDecimal[]{BigDecimal.ZERO};
        //一级代理抽成
        BigDecimal rebateFirst = new BigDecimal(current.getRebatePointGradeOne());
        rebateFirst = rebateFirst.divide(new BigDecimal(100));
        //二级代理抽成
        BigDecimal rebateSecond = new BigDecimal(current.getRebatePointGradeTwo());
        rebateSecond = rebateSecond.divide(new BigDecimal(100));
        //三级代理抽成
        BigDecimal rebateThird = new BigDecimal(current.getRebatePointGradeThree());
        rebateThird = rebateThird.divide(new BigDecimal(100));

        //获取昨天的时间0点0分0秒及23点59分59秒的时间戳
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        long begin = calendar.getTime().getTime()/1000- 24*60*60L;
        long end = calendar.getTime().getTime()/1000;

        FtBetRecordSearch searchBase = new FtBetRecordSearch();
        searchBase.setBegin(begin*1000);
        searchBase.setEnd(end*1000-1L);
        first.forEach(person ->{
            searchBase.setUserId(person.getUsername());
            List<FtBetRecordRes> firstBet = ftBetRecordService.get(searchBase);
            firstBet.forEach(bet->{
                BigDecimal betAmount = bet.getBetAmount();
                firstBets[0] = firstBets[0].add(betAmount);
            });
        });
        second.forEach(person ->{
            searchBase.setUserId(person.getUsername());
            List<FtBetRecordRes> secondBet = ftBetRecordService.get(searchBase);
            secondBet.forEach(bet->{
                BigDecimal betAmount = bet.getBetAmount();
                secondBets[0] = secondBets[0].add(betAmount);
            });
        });

        third.forEach(person ->{
            searchBase.setUserId(person.getUsername());
            List<FtBetRecordRes> thirdBet = ftBetRecordService.get(searchBase);
            thirdBet.forEach(bet->{
                BigDecimal betAmount = bet.getBetAmount();
                thirdBets[0] = thirdBets[0].add(betAmount);
            });
        });
        firstBets[0] = firstBets[0].multiply(rebateFirst);
        secondBets[0] = secondBets[0].multiply(rebateSecond);
        thirdBets[0] = thirdBets[0].multiply(rebateThird);

        BigDecimal yesterdayUnderUserCommission = firstBets[0].setScale(2);
        BigDecimal yesterdayOtherUserCommission = secondBets[0].add(thirdBets[0]).setScale(2);
        DealersInfoRes dealersInfoRes = new DealersInfoRes();
        dealersInfoRes.setOtherUser(second.size()+third.size());
        dealersInfoRes.setUnderUser(first.size());
        dealersInfoRes.setYesterdayUnderUserCommission(yesterdayUnderUserCommission);
        dealersInfoRes.setYesterdayOtherUserCommission(yesterdayOtherUserCommission);
        dealersInfoRes.setYesterdayCommission(yesterdayUnderUserCommission.add(yesterdayOtherUserCommission));
        dealersInfoRes.setTotalCommission(admin.getHistoryMoney());
        BigDecimal[] availableCommission = new BigDecimal[]{BigDecimal.ZERO};
        //获取可领取佣金
        String str = admin.getAvailableCommission();
        List<LowerData> list = JSONObject.parseArray(str, LowerData.class);
        list.forEach(lowerData -> {
            BigDecimal temp = lowerData.getAvailableCommission();
            availableCommission[0] = availableCommission[0].add(temp);
        });
        dealersInfoRes.setAvailableCommission(availableCommission[0]);
        dealersInfoRes.setUsername(admin.getUsername());
        return dealersInfoRes;

    }*/

    @GetMapping("/user/{userId}")
    @ApiOperation(value = "代理-推广信息")
    public AdminRes getAdminInfo(@ApiParam("用户id") @PathVariable("userId")String userId){
        Admin admin = adminService.getByAccount(userId);
        SearchBase searchBase = new SearchBase();
        List<DealersLevel> dealersLevels = dealersLevelService.get(searchBase);
        DealersLevel dealersLevel = dealersLevelService.getById(admin.getLevelId());
        DealersLevel nextLevel = dealersLevelService.getNextLevel(admin.getLevelId());
        AdminRes adminRes = new AdminRes();
        BeanUtils.copyProperties(admin,adminRes);
        adminRes.setLevelName(dealersLevel.getName());
        adminRes.setNextLevelName(nextLevel.getName());
        adminRes.setList(dealersLevels);
        return adminRes;
    }

/*    @GetMapping("/dealersDetail/{userId}")
    @ApiOperation(value = "代理-推广明细")
    public DealersDetailRes getDealersDetail(@ApiParam("用户id") @PathVariable("userId") String userId){
        //当前用户信息
        Admin admin = adminService.getByAccount(userId);
        //直属玩家信息
        List<Admin> first = adminService.getUnderChildren(admin.getUsername());
        //获取可领取佣金
        String str = admin.getAvailableCommission();
        List<LowerData> list = JSONObject.parseArray(str, LowerData.class);
        DealersDetailRes dealersDetailRes = new DealersDetailRes();
        dealersDetailRes.setList(list);
        dealersDetailRes.setTotalCommission(admin.getHistoryMoney());
        dealersDetailRes.setUnderUser(first.size());
        return dealersDetailRes;
    }*/

    @GetMapping("/rankingList/{type}")
    @ApiOperation(value = "代理-推广排行")
    public List<RankingList> getDealersDetail(@ApiParam("排行榜类型（0日1周2月）") @PathVariable("type") Integer type){
        return rankingListService.get(type);
    }

/*    @PostMapping("/extractsRecord")
    @ApiOperation(value = "代理-添加提取记录")@ApiImplicitParams({
            @ApiImplicitParam(name="id",value="记录",required=true),
            @ApiImplicitParam(name="amount",value="金额",required=true),
            @ApiImplicitParam(name="userId",value="用户",required=true),
            @ApiImplicitParam(name="status",value="状态(0提取中，1提取完成，2提取失败)",required=true)
    })
    public ExtractsRecord add(@RequestBody ExtractsRecord extractsRecord){
        extractsRecord.setCreateTime(new Date());
        Admin admin = adminService.getByAccount(extractsRecord.getUserId()+"");
        extractsRecord.setDetail(admin.getAvailableCommission());
        extractsRecordService.add(extractsRecord);
        adminService.update(admin);
        return extractsRecord;
    }*/

    @GetMapping("/extractsRecord")
    @ApiOperation(value = "代理-获取提取记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name="userId",value="用户id",required=true,paramType = "query"),
            @ApiImplicitParam(name="page",value="第几页",required=true,paramType = "query"),
            @ApiImplicitParam(name="limit",value="每页显示数量",required=true,paramType = "query")
    })
    public List<ExtractsRecord> getExtractsRecord(@ApiIgnore ExtractsRecordSearch searchBase){
        PageHelper.startPage(searchBase.getPage(), searchBase.getLimit());
        return extractsRecordService.get(searchBase);
    }


    @PutMapping("/extractsRecord")
    @ApiOperation(value = "代理-编辑提取记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="记录",required=true),
            @ApiImplicitParam(name="status",value="状态(0提取中，1提取完成，2提取失败)",required=true)
    })
    public ExtractsRecord update(@RequestBody ExtractsRecord extractsRecord){

        if(extractsRecord.getStatus()==2){

            while (true){
                int i = adminService.refund(extractsRecord);
                if(i==1){
                    break;
                }
            }
        }
        return extractsRecordService.update(extractsRecord);
    }


    @CacheEvict(value="reward",key="'reward_'+#userId")
    @PostMapping("ftBetRecord")
    @ApiOperation(value = "添加投注记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name="betAmount",value="投注金额",required=true),
            @ApiImplicitParam(name="gameKind",value="游戏分类id",required=true),
            @ApiImplicitParam(name="gamePlatform",value="游戏平台id",required=true),
            @ApiImplicitParam(name="gameId",value="游戏id",required=true),
            @ApiImplicitParam(name="userId",value="用户id",required=true)
    })
    public Map<String,String> addBetRecord(@ApiIgnore FtBetRecord ftBetRecord) {
        Map<String, String> map = new HashMap<>();
        ftBetRecordService.add(ftBetRecord);
        long id = ftBetRecord.getId();
        map.put("result", "success");
        map.put("id", id+"");
        return map;
    }

    @GetMapping("ftBetRecord")
    @ApiOperation(value = "获取投注记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name="gamePlatform",value="游戏平台",required=true),
            @ApiImplicitParam(name="userId",value="用户id",required=true),
            @ApiImplicitParam(name="gameKind",value="游戏种类",required=true),
            @ApiImplicitParam(name="begin",value="开始时间",required=true),
            @ApiImplicitParam(name="end",value="结束时间",required=true),
            @ApiImplicitParam(name="page",value="第几页",required=true),
            @ApiImplicitParam(name="limit",value="每页显示数量",required=true)
    })
    public List<FtBetRecordRes> getBetRecord(@ApiIgnore FtBetRecordSearch searchBase) {
        PageHelper.startPage(searchBase.getPage(), searchBase.getLimit());
        List<FtBetRecordRes> ftBetRecordRes = ftBetRecordService.get(searchBase);
        return ftBetRecordRes;
    }

    @PutMapping("ftBetRecord")
    @ApiOperation(value = "编辑投注记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="投注记录id",required=true),
            @ApiImplicitParam(name="payoutTimeUtc",value="派彩时间",required=true),
            @ApiImplicitParam(name="pieAwarded",value="派彩金额",required=true)
    })
    public Map<String,String> updateBetRecord(@ApiIgnore FtBetRecord ftBetRecord) {
        Map<String, String> map = new HashMap<>();
        ftBetRecordService.update(ftBetRecord);
        map.put("result", "success");
        return map;
    }

    @PostMapping("ftAccountDetails")
    @ApiOperation(value = "添加账户明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name="tradeTime",value="交易时间",required=true),
            @ApiImplicitParam(name="expense",value="支出金额",required=true),
            @ApiImplicitParam(name="income",value="收入金额",required=true),
            @ApiImplicitParam(name="accountBalance",value="账户余额",required=true),
            @ApiImplicitParam(name="tradeType",value="交易方式id",required=true),
            @ApiImplicitParam(name="userId",value="用户id",required=true)
    })
    public Map<String,String> addAccountDetails(@ApiIgnore FtAccountDetails ftAccountDetails) {
        Map<String, String> map = new HashMap<>();
        ftAccountDetailsService.add(ftAccountDetails);
        long id = ftAccountDetails.getId();
        System.out.println(id);
        map.put("result", "success");
        map.put("id", id+"");
        return map;
    }

    @GetMapping("ftAccountDetails")
    @ApiOperation(value = "获取账户明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name="tradeType",value="交易方式id",required=true),
            @ApiImplicitParam(name="userId",value="用户id",required=true),
            @ApiImplicitParam(name="begin",value="开始时间",required=true),
            @ApiImplicitParam(name="end",value="结束时间",required=true),
            @ApiImplicitParam(name="page",value="第几页",required=true),
            @ApiImplicitParam(name="limit",value="每页显示数量",required=true)
    })
    public List<FtAccountDetailsRes> getAccountDetails(@ApiIgnore FtAccountDetailsSearch searchBase) {
        PageHelper.startPage(searchBase.getPage(), searchBase.getLimit());
        List<FtAccountDetailsRes> ftAccountDetailsRes = ftAccountDetailsService.get(searchBase);
        return ftAccountDetailsRes;
    }

    @GetMapping("accountDetailStatistics/{userId}")
    @ApiOperation(value = "获取账户统计")
    public AccountDetailStatisticsRes getSum(@ApiParam("用户id") @PathVariable("userId") Long userId){
        return ftAccountDetailsService.getSum(userId);
    }

    @GetMapping("accountStatistics/{userId}")
    @ApiOperation(value = "获取个人报表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="userId",value="用户id",required=true),
            @ApiImplicitParam(name="gameKind",value="游戏种类",required=true),
            @ApiImplicitParam(name="begin",value="开始时间",required=true),
            @ApiImplicitParam(name="end",value="结束时间",required=true)
    })
    public AccountStatisticsRes getAccountStatistics(@ApiIgnore FtBetRecordSearch searchBase){
        return ftBetRecordService.getAccountStatistics(searchBase);
    }


    @GetMapping("vip")
    @ApiOperation(value = "获取Vip等级")
    public List<FtVip> getVip(){
        return ftVipService.get(null);
    }














//    @GetMapping("/test1")
//    public void test1() throws Exception{
//        testService.test1();
//    }
//
//    @GetMapping("/test2")
//    public void test2() throws Exception{
//        testService.test2();
//    }








}
